import { WS_BASE_URL } from "../../utils/globalConstants";
import { roundhistorylist, bethistorylist,roundbetstat,gameRoomInit } from "@/api/game";
const state = {
    diaLogState: 0,
    gameState:'Prepare',
    betTime: '',
    historydata: '',
    bethistorydata: '',
    socket: '',
    gameResult:'',
    //游戏总积分
    topConfig:0,
    //游戏类型，判断走那个配置
    zonCredit:0,
    //type——1代表单，龙
    type_1:0,
    //比例
    type1_Proportion:0,
     //type——2代表双，虎
    type_2:0,
    //比例
    type2_Proportion:0,
    bifen:''
    //0开始下注1游戏开始2结算//3结算完成算金币
};
const mutations = {
    SET_ZON_CREDIT(state, total) {
        state.zonCredit = total;
      },
      SET_TYPE_1_Proportion(state, data) {
        state.type1_Proportion = data;
      },
      SET_TYPE_2_Proportion(state, data) {
        state.type2_Proportion = data;
      },
      SET_TYPE_1(state, total) {
        state.type_1 = total;
      },
      SET_TYPE_2(state, total) {
        state.type_2 = total;
      },
      SET_BIFEN(state, bifen) {
        state.bifen = bifen;
      },
    SET_TIPS_STATE: (state, diaLogState) => {
        state.diaLogState = diaLogState;
    },
    SET_TOP_CONFIG: (state, topConfig) => {
        state.topConfig = topConfig;
    },
    SET_MSG: (state, betTime) => {
        state.betTime = betTime;
    },
    SET_HISTORYDATA: (state, historydata) => {
        state.historydata = historydata;    
    },
    SET_BETHISTORYDATA: (state, bethistorydata) => {
        state.bethistorydata = bethistorydata;
    },
    SET_SOCKET(state, socket) {
        state.socket = socket;
    },
    SET_GAMESTATE(state, gameState) {
        state.gameState = gameState;
    },
    SET_GAMERESULT(state, gameResult) {
        state.gameResult = gameResult;
    },
    INIT(state){
        state.diaLogState=0,
        state.gameState='Prepare',
        state.betTime='',
        state.historydata='',
        state.bethistorydata='',
        state.socket=''
    }
};
const actions = {
    async startWebsock({ commit, dispatch, rootState, state }) {
        const createWebSocket = () => {
            const UUID = rootState.handlegame.gameInfo.uuid;
            const UUIDTOKEN = localStorage.getItem("UUIDTOKEN");
            const socketUrl = `${WS_BASE_URL}/api/v1/h5/websocket/ws/${UUID}/${UUIDTOKEN}`;
    
            const socket = new WebSocket(socketUrl);
    
            const heartbeatMsg = {
                msgType: 'ping'
            };
    
            let heartbeatInterval;
    
            socket.onopen = () => {
                heartbeatInterval = setInterval(() => {
                    if (socket.readyState === WebSocket.OPEN) {
                        socket.send(JSON.stringify(heartbeatMsg)); // 发送心跳包
                    } else {
                        clearInterval(heartbeatInterval); // 如果连接关闭，停止发送心跳包
                        createWebSocket(); // 重新连接
                    }
                }, 5000); // 每隔5秒发送一次心跳包，你可以根据需要调整时间间隔
            };
    
            socket.onmessage = (event) => {
                let newData = {};
                if (typeof event.data === 'string') {
                    newData = JSON.parse(event.data);
                } else {
                    newData = event.data;
                }
                if (newData.msgType === "betTime") {
                    commit('SET_MSG', newData.msg);
                    if(newData.msg === 0){
                        console.log('停止下注');
                    }
                    commit('SET_GAMESTATE', 'betTime');
                }
                if (newData.msgType === "roundResult") {
                    dispatch('getHisToryList', 'GETbethistorylist');
                }
                if (newData.msgType === "startBet") {
                    commit('SET_ZON_CREDIT', 0);
                    commit('SET_TYPE_1', 0);
                    commit('SET_TYPE_2', 0);
                    dispatch('calculate');
                    commit('SET_GAMESTATE', 'startBet');
                }
                if (newData.msgType === "stopBet") {
                    commit('SET_GAMESTATE', 'stopBet');
                }
                if (newData.msgType === "orderResult" || newData.msgType === "roomOrderResult") {
                    commit('SET_GAMESTATE', newData.msgType);
                    commit('SET_GAMERESULT', newData);
                    console.log('触发');
                    dispatch('user/getMineInfo', null, { root: true });
                    dispatch('websock/getHisToryList', null, { root: true });
                    dispatch('websock/GETbethistorylist', null, { root: true });
                }
                if (newData.msgType === "roomRuleStat") {
                    var listData = newData.ruleStat;
                    var figData = {};
                    var type_1 = {};
                    var type_2 = {};
                    var filterKeys = [];
                    var type_1keys = [];
                    var type_2keys = [];
                    if (state.topConfig === 1) {
                        filterKeys = ['TOP1_DAN', 'TOP2_DAN', 'TOP3_DAN', 'TOP1_SHUANG', 'TOP2_SHUANG', 'TOP3_SHUANG'];
                        type_1keys = ['TOP1_DAN', 'TOP2_DAN', 'TOP3_DAN'];
                        type_2keys = ['TOP1_SHUANG', 'TOP2_SHUANG', 'TOP3_SHUANG'];
                    }
                    if (state.topConfig === 2) {
                        filterKeys = ['TOP1_LONG', 'TOP2_LONG', 'TOP3_LONG', 'TOP4_LONG', 'TOP1_HU', 'TOP2_HU', "TOP3_HU", "TOP4_HU"];
                        type_1keys = ['TOP1_LONG', 'TOP2_LONG', 'TOP3_LONG', 'TOP4_LONG'];
                        type_2keys = ['TOP1_HU', 'TOP2_HU', "TOP3_HU", "TOP4_HU"];
                    }
                    if (state.topConfig === 3) {
                        filterKeys = ['TOP1_RED', 'TOP1_GREEN', 'TOP1_PURPLE'];
                        type_1keys = ['TOP1_GREEN', 'TOP1_PURPLE'];
                        type_2keys = ['TOP1_RED'];
                    }
                    const sumCredit = (obj) => {
                        return Object.values(obj).reduce((acc, item) => {
                          return acc + (item.Credit || 0);
                        }, 0);
                    };
                    figData = Object.keys(listData)
                    .filter(key => filterKeys.includes(key))
                    .reduce((result, key) => {
                        result[key] = listData[key];
                        return result;
                    }, {});
                    figData.totalCredit = sumCredit(figData);
                    type_1 = Object.keys(listData)
                    .filter(key => type_1keys.includes(key))
                    .reduce((result, key) => {
                        result[key] = listData[key];
                        return result;
                    }, {});
                    type_1.totalCredit = sumCredit(type_1);
                    type_2 = Object.keys(listData)
                    .filter(key => type_2keys.includes(key))
                    .reduce((result, key) => {
                        result[key] = listData[key];
                        return result;
                    }, {});
                    type_2.totalCredit = sumCredit(type_2);
                    commit('SET_ZON_CREDIT', figData.totalCredit);
                    commit('SET_TYPE_1', type_1.totalCredit);
                    commit('SET_TYPE_2', type_2.totalCredit);
                    dispatch('calculate');
                }
            };
    
            socket.onclose = (event) => {
                console.log("WebSocket 连接已关闭:", event);
                // 处理连接关闭
                clearInterval(heartbeatInterval); // 停止心跳包
                createWebSocket(); // 重新连接
            };
    
            socket.onerror = (error) => {
                console.error("WebSocket 错误:", error);
                // 处理连接错误
                clearInterval(heartbeatInterval); // 停止心跳包
                createWebSocket(); // 重新连接
            };
    
            // 存储WebSocket实例到状态
            commit('SET_SOCKET', socket);
        };
    
        // 创建WebSocket实例
        createWebSocket();
    },
    
    closeWebsock({ state }) {
        if (state.socket) {
            state.socket.close();
        }
    },

    async Getroundbetstat({rootState ,state,commit,dispatch}) {
        var otherModuleData = rootState.handlegame.gameInfo;
        let e = {
            gameRoundNo: otherModuleData.gameRoundNo,
            gameRoomUuid: otherModuleData.uuid
        };
        roundbetstat(e).then(res => {
            try {
                var listData = res.data.data;
                // 使用filter筛选指定ruleId的元素
                var figData= []
                //type1代表单，龙，type2代表双，虎
                var type_1 = []
                var type_2 = []
                if(state.topConfig===1){
                     figData = listData.filter(function(item) {
                        return (
                            item.ruleId === 'TOP1_DAN' ||
                            item.ruleId === 'TOP2_DAN' ||
                            item.ruleId === 'TOP3_DAN' ||
                            item.ruleId === 'TOP1_SHUANG' ||
                            item.ruleId === 'TOP2_SHUANG' ||
                            item.ruleId === 'TOP3_SHUANG'
                        );
                    });
           
                    type_1 = listData.filter(function(item) {
                        return (
                            item.ruleId === 'TOP1_DAN' ||
                            item.ruleId === 'TOP2_DAN' ||
                            item.ruleId === 'TOP3_DAN' 
                        );
                    });
                    type_2 = listData.filter(function(item) {
                        return (
                            item.ruleId === 'TOP1_SHUANG' ||
                            item.ruleId === 'TOP2_SHUANG' ||
                            item.ruleId === 'TOP3_SHUANG'
                        );
                    });
                 }
                 if(state.topConfig===2){
                     figData = listData.filter(function(item) {
                        return (
                            item.ruleId === 'TOP1_LONG' ||
                            item.ruleId ==="TOP2_LONG" ||
                            item.ruleId ==="TOP3_LONG" ||
                            item.ruleId ==="TOP4_LONG" ||
                            item.ruleId === 'TOP1_HU' ||
                            item.ruleId ==="TOP2_HU" ||
                            item.ruleId ==="TOP3_HU" ||
                            item.ruleId ==="TOP4_HU" 
                        );
                    });
                    type_1 = listData.filter(function(item) {
                        return (
                            item.ruleId === 'TOP1_LONG' ||
                            item.ruleId ==="TOP2_LONG" ||
                            item.ruleId ==="TOP3_LONG" ||
                            item.ruleId ==="TOP4_LONG" 
                        );
                    });
                    type_2 = listData.filter(function(item) {
                        return (
                            item.ruleId === 'TOP1_HU' ||
                            item.ruleId ==="TOP2_HU" ||
                            item.ruleId ==="TOP3_HU" ||
                            item.ruleId ==="TOP4_HU" 
                        );
                    });
                 }
                 if(state.topConfig===3){
                    figData = listData.filter(function(item) {
                       return (
                           item.ruleId === 'TOP1_RED' ||
                           item.ruleId ==="TOP1_GREEN" ||
                           item.ruleId ==="TOP1_PURPLE" 
                       );
                   });
                   type_1 = listData.filter(function(item) {
                       return (
                           item.ruleId === 'TOP1_GREEN' ||
                           item.ruleId ==="TOP1_PURPLE"
                       );
                   });
                   type_2 = listData.filter(function(item) {
                       return (
                           item.ruleId === 'TOP1_RED' 
                       );
                   });
                }
                const figDataTotal = figData.reduce(function (acc, item) {
                    return acc + (item.sumCredit || 0); // 使用0作为默认值，防止item.sumCredit为undefined
                  }, 0);
        
                  // 计算type_1中sumCredit的总和
                  const type_1Total = type_1.reduce(function (acc, item) {
                    return acc + (item.sumCredit || 0);
                  }, 0);
                  // 计算type_2中sumCredit的总和
                  const type_2Total = type_2.reduce(function (acc, item) {
                    return acc + (item.sumCredit || 0);
                  }, 0);
                  commit('SET_ZON_CREDIT',figDataTotal);
                  commit('SET_TYPE_1',type_1Total);
                  commit('SET_TYPE_2',type_2Total);
                  dispatch('calculate');
                  return Promise.resolve(); // 返回 Promise 表示异步操作已完成
            } catch (error) {
                return Promise.reject(false);
              }
          
        });      
        let r = {
            gameRoundNo: otherModuleData.gameRoundNo,
            gameRoomUuid: otherModuleData.uuid
        };
        gameRoomInit(r).then(res=>{
            var gameState = res.data.data.gameRoom.gameState
            //为投注游戏
            if(gameState===2){
                commit('SET_GAMESTATE',"betTime");
            }
            //
            if(gameState===3){
                commit('SET_GAMESTATE',"Settlement");
            }
            if(gameState===4){
                commit('SET_GAMESTATE',"Settlement");
            }
        })
    },
    async calculate({state,commit}){
        const zonCredit = state.zonCredit;
        let type1Percentage = 0;
        let type2Percentage = 0;
        if (zonCredit !== 0) {
            type1Percentage = (state.type_1 / zonCredit) * 100;
            type2Percentage = (state.type_2 / zonCredit) * 100;
        }
        let type1ToType2Ratio;
        if (state.type_1 === 0 && state.type_2 === 0) {
          type1ToType2Ratio = "0:0"; // 如果两者都是0，则返回 0:0
        } else if (state.type_1 === 0) {
          type1ToType2Ratio = `0:${state.type_2}`; // 如果 type_1 是0，则返回 0:type_2
        } else if (state.type_2 === 0) {
          type1ToType2Ratio = `${state.type_1}:0`; // 如果 type_2 是0，则返回 type_1:0
        } else {
          type1ToType2Ratio = `${state.type_1}:${state.type_2}`; // 其他情况返回 type_1:type_2
        }
        commit('SET_BIFEN',type1ToType2Ratio)
        commit('SET_TYPE_1_Proportion', Math.floor(type1Percentage) / 100);
        commit('SET_TYPE_2_Proportion', Math.floor(type2Percentage) / 100);
    },
    //计算数据
    async getHisToryList({ commit, rootState }) {
        var otherModuleData = rootState.handlegame.gameInfo;
        let e = {
            gameRoomUuid: otherModuleData.uuid
        };
        roundhistorylist(e).then(res => {
            commit('SET_HISTORYDATA', res.data.data.list);
        });
    },
    async GETbethistorylist({ commit, rootState }) {
        var otherModuleData = rootState.handlegame.gameInfo;
        let e = {
            gameRoomUuid: otherModuleData.uuid
        };
        bethistorylist(e).then(res => {
            console.log(res.data.data.list);
            commit('SET_BETHISTORYDATA', res.data.data.list);
        });
    },
};

export default {
    namespaced: true,
    state,
    mutations,
    actions
};
